package ludowork.core;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class PluginLoader {

    public PluginLoader(String pluginsPath) {
        this.pluginPath = pluginsPath;
    }

    public void loadPlugins() {
        FilenameFilter textFilter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                String lowercaseName = name.toLowerCase();
                if (lowercaseName.endsWith("jar")) {
                    return true;
                }
                return false;
            }
        };
        File folder;
        File[] jars;
        System.out.print("Plugin search folder: " + getPluginsPath() + "\n");
        try {
            folder = new File(getPluginsPath());
            jars = folder.listFiles(textFilter);
        } catch (Exception e) {
            return;
        }
        if (jars == null) {
            return; //No jars in folder!
        }
        for (int i = 0; i < jars.length; i++) {
            File jar = jars[i];
            try {
                addFile(jar);
                System.out.printf("Loaded " + jar.getName() + "\n");
            } catch (IOException ex) {
                System.out.printf("Cant load " + jar.getName() + "\n");
            }
        }
    }

    public String getPluginsPath() {
        return new File(System.getProperty("user.dir") + "/" + pluginPath ).getAbsolutePath();
    }

    public void addFile(String s) throws IOException {
        File f = new File(s);
        addFile(f);
    }
    
    public void addFile(File f) throws IOException {
        addURL(f.toURI().toURL());
    }
    
    public void addURL(URL u) throws IOException {
        URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        final Class[] parameters = new Class[]{URL.class};
        Class sysclass = URLClassLoader.class;
        try {
            Method method = sysclass.getDeclaredMethod("addURL", parameters);
            method.setAccessible(true);
            method.invoke(sysloader, new Object[]{u});
        } catch (Throwable t) {
            throw new IOException("Cant and given URL to class path: " + t.getMessage());
        }
    }
    
    private String pluginPath;
}
